<script setup lang="ts">
import { deleteApi, getAppApiList, getAppDetail, changeStatus } from '@/api/app-list/app-list'
import useDictStore from '@/store/modules/dict'
import { ModalShowType } from '@/types/common'
import { Ref, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import NewApi from './new-api.vue'
import EditApp from './new-app-modal.vue'
import { message } from '@/utils/message'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/modules/user'

const router = useRouter()

const { api_type, app_type } = useDictStore().getDicts('api_type', 'app_type')
const route = useRoute()
const termId = route.query.id as string

const enableSwitchLoading = ref(false)
const enablePrivateSwitchLoading = ref(false)
const flag = ref(false)
const activeName = ref('appDetail')
const columnsPrivate: TableColumnList = [
  {
    label: '接口名称',
    prop: 'apiName',
    minWidth: 100,
  },
  {
    label: '接口路径',
    prop: 'requestPath',
    minWidth: 150,
  },
  {
    label: '接口类型',
    prop: 'apiType',
    minWidth: 100,
    formatter({ apiType }) {
      return api_type.getLabel(apiType)
    },
  },
  {
    label: '接口启用',
    slot: 'gxIsEnabledPrivate',
    minWidth: 100,
  },
  {
    label: '操作',
    fixed: 'right',
    width: 180,
    slot: 'operation',
  },
]

const columnsPublic: TableColumnList = [
  {
    label: '接口名称',
    prop: 'apiName',
    minWidth: 100,
  },
  {
    label: '接口路径',
    prop: 'requestPath',
    minWidth: 150,
  },
  {
    label: '接口类型',
    prop: 'apiType',
    minWidth: 100,
    formatter({ apiType }) {
      return api_type.getLabel(apiType)
    },
  },
  {
    label: '接口启用',
    slot: 'gxIsEnabledPublic',
    minWidth: 100,
  },
  {
    label: '操作',
    fixed: 'right',
    width: 180,
    slot: 'operation',
  },
]
const publicDataList = ref([])
const privateDataList = ref([])
const appDetail = ref({}) as Ref<any>
const loading = ref(false)
const apiType = ref<'private' | 'public'>()

const onSearch = async () => {
  loading.value = true
  appDetail.value = (await getAppDetail(route.query.id as string)).data
  publicDataList.value = (
    await getAppApiList({
      publicOrPrivate: 'public',
      gxAppId: route.query.id,
      pageNum: 1,
      pageSize: 999,
    })
  ).rows
  privateDataList.value = (
    await getAppApiList({
      publicOrPrivate: 'private',
      gxAppId: route.query.id,
      pageNum: 1,
      pageSize: 999,
    })
  ).rows
  loading.value = false
}

async function onRemoveApi(id: string) {
  loading.value = true
  await deleteApi(id).finally(() => (loading.value = false))
  message('删除成功', { type: 'success' })
  onSearch()
}

const modalShowEditApp = ref(ModalShowType.Hide)
const modalShowNewApi = ref(ModalShowType.Hide)

// watch(
//   () => route.params.id,
//   async newId => {
//     appDetail.value = await getAppDetail(newId);
//   }
// );
onSearch()

watch(activeName, () => {
  onSearch()
})

const idsList = ref([])

const getApiIds = () => {
  idsList.value = []
  idsList.value = idsList.value.concat(privateDataList.value.map((v) => v.id))
  idsList.value = idsList.value.concat(publicDataList.value.map((v) => v.id))
}

const checkPrivateOps = (rowUserName) => {
  if (useUserStore().isAdmin || useUserStore().userAccountName == rowUserName) {
    return false
  } else {
    return true
  }
}

const checkPublicOps = () => {
  if (useUserStore().isAdmin) {
    return false
  } else {
    return true
  }
}
</script>

<template>
  <div v-loading="loading" class="p-4">
    <div class="bg-el-bg" style="position: relative">
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="应用详情" name="appDetail">
          <section-info>
            <template #title>应用信息</template>
            <template #operation
              ><el-button link type="primary" @click="modalShowEditApp = ModalShowType.Edit"
                >编辑</el-button
              ></template
            >
            <el-row>
              <el-col :span="2">应用名称：</el-col>
              <el-col :span="10">{{ appDetail.appName }}</el-col>
              <el-col :span="2">发布时间：</el-col>
              <el-col :span="10">{{ appDetail.publishTime }}</el-col>
            </el-row>
            <el-row>
              <el-col :span="2">应用属性：</el-col>
              <el-col :span="10">{{ app_type.getLabel(appDetail.appAttribute) }}</el-col>
              <el-col :span="2">应用标签：</el-col>
              <el-col :span="10">{{ appDetail.appLabel }}</el-col>
            </el-row>
            <el-row>
              <el-col :span="2">应用简介：</el-col>
              <el-col :span="10">{{ appDetail.appIntroduce }}</el-col>
            </el-row>
          </section-info>
          <section-info>
            <template #title>应用凭证</template>
            <table>
              <colgroup>
                <col class="w-[100px]" />
              </colgroup>
              <tr>
                <td>AppId:</td>
                <td><copy-text :content="String(route.query.id)" /></td>
              </tr>
              <tr>
                <td>AppCode:</td>
                <td><copy-text :content="appDetail.appCode" /></td>
              </tr>
              <tr>
                <td>AppSecret:</td>
                <td><copy-text :content="appDetail.appSecret" /></td>
              </tr>
              <tr>
                <td>AppKey:</td>
                <td><copy-text :content="appDetail.appKey" /></td>
              </tr>
            </table>
          </section-info>
          <section-info>
            <template #title>联系人信息</template>
            <el-row>
              <el-col :span="2">归属部门：</el-col>
              <el-col :span="10">{{ appDetail.deptName }}</el-col>
              <el-col :span="2">应用联系人：</el-col>
              <el-col :span="10">{{ appDetail.appContact }}</el-col>
            </el-row>
            <el-row>
              <el-col :span="2">联系电话：</el-col>
              <el-col :span="10">{{ appDetail.appContactPhone }}</el-col>
            </el-row>
          </section-info>
        </el-tab-pane>
        <el-tab-pane label="API接口" name="interface">
          <div class="m-4">
            <div>应用名称：{{ appDetail.appName }}</div>
            <div>应用属性：{{ app_type.getLabel(appDetail.appAttribute) }}</div>
          </div>
          <section-info>
            <template #title>已添加的公共接口</template>
            <template #operation>
              <el-button
                v-auth="'manage:appApi:add'"
                type="primary"
                @click="
                  () => {
                    getApiIds()
                    modalShowNewApi = ModalShowType.New
                    apiType = 'public'
                  }
                "
              >
                添加新接口
              </el-button>
            </template>
            <pure-table
              border
              align-whole="center"
              showOverflowTooltip
              table-layout="auto"
              :loading="loading"
              :data="publicDataList"
              :columns="columnsPublic"
              :header-cell-style="{
                background: 'var(--el-table-row-hover-bg-color)',
                color: 'var(--el-text-color-primary)',
              }"
            >
              <template #gxIsEnabledPublic="{ row }">
                <el-switch
                  v-model="row.gxIsEnabled"
                  v-loading="enableSwitchLoading"
                  :disabled="checkPublicOps()"
                  active-value="1"
                  inactive-value="0"
                  :before-change="
                    () => {
                      enableSwitchLoading = true
                      flag = false
                      changeStatus({
                        gxId: row.gxId,
                        gxIsEnabled: row.gxIsEnabled == '1' ? '0' : '1',
                      })
                        .then((res: any) => {
                          if (res.code == 200) {
                            message('操作成功', { type: 'success' })
                            enableSwitchLoading = false
                            row.gxIsEnabled = row.gxIsEnabled == '1' ? '0' : '1'
                            flag = true
                          } else {
                            message('操作失败，管理员才允许操作', { type: 'error' })
                          }
                        })
                        .catch((err) => {
                          message('操作失败:' + err, { type: 'error' })
                        })
                        .finally(() => {
                          enableSwitchLoading = false
                        })
                      return flag
                    }
                  "
                />
              </template>
              <template #operation="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="
                    router.push({
                      path: '/api-manage/detail',
                      query: { id: row.id },
                    })
                  "
                >
                  接口详情
                </el-button>
                <el-popconfirm title="是否确认删除?" @confirm="() => onRemoveApi(row.gxId)">
                  <template #reference>
                    <el-button v-auth="'manage:appApi:remove'" link type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </pure-table>
          </section-info>
          <section-info>
            <template #title>我创建的私有接口</template>
            <template #operation
              ><el-button
                v-auth="'manage:appApi:add'"
                type="primary"
                @click="
                  () => {
                    getApiIds()
                    modalShowNewApi = ModalShowType.New
                    apiType = 'private'
                  }
                "
                >添加私有接口</el-button
              ></template
            >
            <pure-table
              border
              align-whole="center"
              showOverflowTooltip
              table-layout="auto"
              :loading="loading"
              :data="privateDataList"
              :columns="columnsPrivate"
              :header-cell-style="{
                background: 'var(--el-table-row-hover-bg-color)',
                color: 'var(--el-text-color-primary)',
              }"
            >
              <template #gxIsEnabledPrivate="{ row }">
                <el-switch
                  v-model="row.gxIsEnabled"
                  v-loading="enablePrivateSwitchLoading"
                  :disabled="checkPrivateOps(row.createBy)"
                  active-value="1"
                  inactive-value="0"
                  :before-change="
                    () => {
                      enablePrivateSwitchLoading = true
                      flag = false
                      changeStatus({
                        gxId: row.gxId,
                        gxIsEnabled: row.gxIsEnabled == '1' ? '0' : '1',
                      })
                        .then((res: any) => {
                          if (res.code == 200) {
                            message('操作成功', { type: 'success' })
                            enablePrivateSwitchLoading = false
                            row.gxIsEnabled = row.gxIsEnabled == '1' ? '0' : '1'
                            flag = true
                          } else {
                            message('操作失败，管理员或创建者本人才允许操作', { type: 'error' })
                          }
                        })
                        .catch((err) => {
                          message('操作失败:' + err, { type: 'error' })
                        })
                        .finally(() => {
                          enablePrivateSwitchLoading = false
                        })
                      return flag
                    }
                  "
                />
              </template>
              <template #operation="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="
                    router.push({
                      path: '/api-manage/detail',
                      query: { id: row.id },
                    })
                  "
                >
                  接口详情
                </el-button>
                <el-popconfirm title="是否确认删除?" @confirm="() => onRemoveApi(row.gxId)">
                  <template #reference>
                    <el-button v-auth="'manage:appApi:remove'" link type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template></pure-table
            >
          </section-info>
        </el-tab-pane>
      </el-tabs>
      <el-button
        type="primary"
        style="position: absolute; right: 10px; top: 5px"
        @click="router.back()"
        >返回</el-button
      >
    </div>
    <EditApp v-model:modalShow="modalShowEditApp" :onSearch="onSearch" :termId="termId" />
    <NewApi
      v-model:modalShow="modalShowNewApi"
      :apiType="apiType"
      :termId="termId"
      :api-ids="idsList"
      @search="onSearch"
    />
  </div>
</template>
